package com.cloud.class04.test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class SemaphoreExample {
    public static void main(String[] args) {
//        创建一个具有4个许可的信号量车位
        Semaphore semaphore = new Semaphore(4);

        //固定线程池
//        相当于创建了8个线程来模拟8个人
        ExecutorService executorService = Executors.newFixedThreadPool(8);
        for (int i = 0; i < 8; i++) {//模拟8个人依次抢占车位
//            submit作用是提交一个任务到线程池中，并返回一个Future对象，该对象可以获取任务执行结果
            executorService.submit(new Task(semaphore, i));
        }
        //关闭线程池
        executorService.shutdown();
    }

    static class Task implements Runnable {
        private Semaphore semaphore;
        private int id;

        public Task(Semaphore semaphore, int id) {
            this.semaphore = semaphore;
            this.id = id;
        }

        @Override
        public void run() {
//            获取许可
            try {
                semaphore.acquire();
                System.out.println("线程" + Thread.currentThread().getName() + "进了一辆车，安全停放");
                Thread.sleep(2000);
                System.out.println("线程" + Thread.currentThread().getName() + "离开了一辆车");
//                release释放许可
                semaphore.release();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
